<?php


namespace app\api\controller\xilumarket;


use app\common\controller\Api;
use app\common\model\xilumarket\ExpressCompany;
use app\common\model\xilumarket\Third;
use app\common\model\xilumarket\Order AS OrderModel;
use fast\Http;
use think\Exception;
use think\Hook;
use function fast\array_get;

class Order extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * 售后页信息
     */
    public function aftersale_goods(){
        $params = $this->request->param('');
        if($order_id = array_get($params,'order_id')){
            $order = OrderModel::with(['orderProduct'=>function($query){
                $query->field(['id','order_id','product_id','product_name','image','product_price','sum_price']);
            }])->field(['id','order_no','pay_price','total_price','total_price','freight_type','pay_status','freight_status','order_status','refund_status','receipt_status','comment_status'])->where('id',$order_id)->find();
            $this->success("",$order);
        }else{
            $this->error("参数错误");
        }
    }

    /**
     * 订单确认
     */
    public function sure(){
        $params = $this->request->param('');
        #1.获取商品-下单地址
        try {
            $result = OrderModel::sure($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('',$result);
    }

    /**
     * 下单
     */
    public function create_order(){
        $params = $this->request->param('');
        $user = $this->auth->getUser();
        if($user->status != 'normal') {
            throw new Exception('账户已被禁用');
        }
        #1.获取商品
        try {
            $result = OrderModel::create_order($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('',$result);
    }

    /**
     * 用户订单列表
     * @throws \think\exception\DbException
     */
    public function lists(){
        $params = $this->request->param('');
        $result = OrderModel::orderList($params,$this->auth->id);

        $this->success('',$result);
    }

    /**
     * 订单详情
     */
    public function order_detail(){
        trace($this->auth->getToken(), 'token');
        $params = $this->request->param('');
        if(!$params['order_id']){
            $this->error("订单参数错误");
        }
        $result = OrderModel::order_detail($params);
        $result['is_delivery'] = $result['deliveryuser'] && $result['deliveryuser']->user_id == $this->auth->getUser()->id;
        $this->success('',$result);
    }

    /**
     * 订单取消
     * @throws \think\exception\DbException
     */
    public function cancel(){
        $params = $this->request->param('');
        if(!$params['order_id']){
            $this->error("订单参数错误");
        }
        try {
            $result = OrderModel::cancel($params);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('取消成功',$result);
    }

    /**
     * 确认收货
     * @throws \think\exception\DbException
     */
    public function receive(){
        $params = $this->request->param('');
        if(!$params['order_id']){
            $this->error("订单参数错误");
        }
        try {
            $result = OrderModel::receive($params);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('',$result);
    }

    /**
     * 我卖出的商品
     */
    public function sale_lists(){
        $params = $this->request->param('');

        $result = OrderModel::saleLists($params,$this->auth->id);

        $this->success('',$result);
    }

    /**
     * 订单详情
     */
    public function seller_detail(){
        $params = $this->request->param('');
        if(!$params['order_id']){
            $this->error("订单参数错误");
        }
        $result = OrderModel::sellerDetail($params);

        $this->success('',$result);
    }

    /**
     * 物流公司
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function express_company(){
        $lists = ExpressCompany::field("id,name")->where('status','1')->order('id','asc')->select();
        $this->success('',$lists);

    }
    /**
     * 发货
     */
    public function send_freight(){
        $params = $this->request->post('');
        try {
            $ret = OrderModel::sendFreight($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $ret->relationQuery(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'order_product'=>function($query){
                $query->field(['id','order_id','product_name','image','product_price','sum_price']);
            }]);
        $this->success('',$ret);
    }

    /**
     * 自提发货
     */
    public function send_address(){
        $params = $this->request->post('');
        try {
            $ret = OrderModel::sendAddress($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $ret->relationQuery(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'order_product'=>function($query){
                $query->field(['id','order_id','product_name','image','product_price','sum_price']);
            }]);
        $this->success('',$ret);
    }

    /**
     * 物流
     */
    public function logistics(){
        $order_id = $this->request->param('order_id');
        $order = $order_id?OrderModel::where('id',$order_id)->find() : null;
        if(!$order || $order->freight_status != 1){
            $this->error('未有物流信息');
        }
        $config = \app\common\model\xilumarket\Config::getMyConfig('logistics');
        $code = $order->express_code;
        //参数设置
        $key = $config['logistics_key'];                        // 客户授权key
        $customer = $config['logistics_customer'];                   // 查询公司编号
        $param = array (
            'com' => $code,             // 快递公司编码
            'num' => $order->express_no, // 快递单号
            'phone' => $order->order_address?$order->order_address->mobile : '',                // 手机号
            'from' => '',                 // 出发地城市
            'to' => '',                   // 目的地城市
            'resultv2' => '1',            // 开启行政区域解析
            'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
        );
        //请求参数
        $post_data = array();
        $post_data['customer'] = $customer;
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sign = md5($post_data['param'].$key.$post_data['customer']);
        $post_data['sign'] = strtoupper($sign);
        $url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址
        $result = Http::get($url,$post_data);
        $data = json_decode($result, true);
        if(isset($data['returnCode'])){
            $msg = $data['message'];
            $logistics = [];
        }else{
            $msg = '';
            $logistics = $data['data'];
            foreach ($logistics as $key=>$logistic){
                $time = strtotime($logistic['ftime']);
                $logistics[$key]['date'] = date('m-d',$time);
                $logistics[$key]['time'] = date('H:i',$time);
            }
        }
        $this->success($msg,['logistics'=>$logistics,'order'=>$order]);
    }

}